﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Linq;
using Microsoft.SharePoint.Administration;
using System.Collections.Generic;

namespace P3.Modules.SharePoint.AutoTag.AutoTagEmailER
{
    /// <summary>
    /// List Email Events
    /// </summary>
    public class AutoTagEmailER : SPEmailEventReceiver
    {
        AutoTag.AutoTagER.AutoTagER autoTagEr = new AutoTagER.AutoTagER();

       /// <summary>
       /// The list received an e-mail message.
       /// </summary>
       public override void EmailReceived(SPList list, SPEmailMessage emailMessage, String receiverData)
       {
           base.EmailReceived(list, emailMessage, receiverData);

           foreach (SPEmailAttachment attachment in emailMessage.Attachments)
           {
               byte[] attachmentArray = new byte[attachment.ContentStream.Length];
               attachment.ContentStream.Read(attachmentArray, 0, (int)attachment.ContentStream.Length);
               SPFileCollection fileColl = list.RootFolder.Files;
               string attachmentFileName = attachment.FileName;

               string[] fileNames = (from SPFile spFile in fileColl
                                     where spFile != null
                                     select spFile.Name).ToArray();

               if (fileNames.Count() > 0)
               {
                   bool fileNameExists = false;
                   fileNameExists = fileNames.Contains(attachmentFileName);
                   int count = 1;

                   while (fileNameExists == true)
                   {
                       attachmentFileName = string.Format("({0})_{1}", count, attachment.FileName);
                       count++;
                       fileNameExists = fileNames.Contains(attachmentFileName);
                   }
               }

               SPFile file = list.RootFolder.Files.Add(attachmentFileName, attachmentArray);
               SPListItem item = file.ListItemAllFields;

               string MultiLineTextField = getConfiguredMultiLineText(item.ParentList, item.ParentList.ParentWeb);

               if (!string.IsNullOrEmpty(MultiLineTextField))
               {
                   try
                   {
                       item[MultiLineTextField] = filterHashValues(emailMessage.PlainTextBody);

                       SPUser user = list.ParentWeb.AllUsers.GetByEmail(emailMessage.Sender);
                       SPFieldUserValue oUser = new SPFieldUserValue(list.ParentWeb, user.ID, user.LoginName);

                       if (user != null)
                       {
                           item["Author"] = oUser;
                           item["Editor"] = oUser;
                       }

                       item.Update();
                   }
                   catch (Exception ex)
                   {
                       SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("P3 AutoTagging Email ER", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
                   }
               }
           }
       }

       private string getConfiguredMultiLineText(SPList sPList,SPWeb web)
       {
           string propertyValue = autoTagEr.getPropertyValue(sPList.ID.ToString(), web);

           string[] fieldNames = null;

           if (propertyValue != "")
           {
               if (propertyValue.Contains("$") == true)
               {
                   string[] seperator = { "$" };
                   fieldNames = propertyValue.Split(seperator, StringSplitOptions.None);
                   if (fieldNames.Length == 2)
                   {
                       return fieldNames[0];
                   }
               }
           }

           return string.Empty;
       }

       private string filterHashValues(string plainText)
       {
           string [] term = null;
           int endtag;

           if ((!string.IsNullOrEmpty(plainText)) && (plainText.Contains("#") == true))
           {
               plainText = plainText.Replace(Environment.NewLine, " ").Replace("\r", " ");

               List<int> positions = autoTagEr.AllIndexesOf(plainText, "#");
               int j = 0;
               term = new string[positions.Count];
               foreach (int i in positions)
               {
                   endtag = plainText.IndexOf(" ", i);
                   if (endtag == -1)
                       term[j] = plainText.Substring(i + 1);
                   else
                       term[j] = plainText.Substring(i + 1, (endtag - i));
                   term[j] = term[j].Replace('_', ' ');
                   j++;
               }
               if (term.Length > 0)
               {
                   return string.Concat("#",string.Join("#", term));
               }
           }

           return string.Empty;
       }
    }
}
